package com.nuoniu.sibanyun.service.erp.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.dto.DynamicReportDto;
import com.nuoniu.sibanyun.entity.dto.ErpVoucherDesignSearchDto;
import com.nuoniu.sibanyun.entity.erp.ErpReportDesign;
import com.nuoniu.sibanyun.mapper.erp.ErpReportDesignMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpReportDesignService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import com.nuoniu.sibanyun.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2021-01-19
 */
@Service
public class ErpReportDesignServiceImpl extends ServiceImpl<ErpReportDesignMapper, ErpReportDesign> implements IErpReportDesignService {

    @Autowired
    private IErpAccountService erpAccountService;


    @Override
    public List<ErpReportDesign> list(String reportCode) {
        QueryWrapper<ErpReportDesign> queryWrapper = new QueryWrapper();
        queryWrapper.eq("report_code",reportCode);
        queryWrapper.orderByAsc("sort");
        List<ErpReportDesign> list = list(queryWrapper);
        return list;
    }

    @Override
    public Page<HashMap<String,Object>> pageReport(DynamicReportDto dynamicReportDto) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = erpAccountService.getCurrentAccountId();
        List<ErpReportDesign> erpReportDesignList = dynamicReportDto.getErpReportDesignList();
        Page<HashMap<String,Object>> page = dynamicReportDto.getPage();

        HashMap<String,Object> paramMap = new HashMap<>();
        //组装参数
        getDynamicParamMap(paramMap,erpReportDesignList);

        if(erpReportDesignList.size() == 0)throw new NuoNiuException("请传递参数");
        ErpReportDesign erpReportDesign = erpReportDesignList.get(0);
        String reportCode = erpReportDesign.getReportCode();

        if (reportCode.contains("_Detail_")){
            checkDesign(erpReportDesignList,"_Detail_");
            page = baseMapper.reportDetailDynamicPage(userInfo.getCompanyId(),currentAccountId,dynamicReportDto,paramMap,page);

        }else if(reportCode.contains("_Statistic_")){
            //校验 字段设计
            checkDesign(erpReportDesignList,"_Statistic_");
            page = baseMapper.reportStatisticDynamicPage(userInfo.getCompanyId(),currentAccountId,dynamicReportDto,paramMap,page);
        }
        //是否 合计
        Boolean isSum = dynamicReportDto.getIsSum();
        long total = page.getTotal();
        int size = page.getRecords().size();
        long pageSize = page.getSize() + 1;
        if (null !=isSum && isSum && size < pageSize &&  size > 0 ){
            boolean match = erpReportDesignList.stream().anyMatch(ErpReportDesign::getOnSummary);
            if (match){
                HashMap<String, Object> map = baseMapper.sumDynamic(userInfo.getCompanyId(), currentAccountId, dynamicReportDto, paramMap);
                if(null != map){
                    map.put("isSum",true);
                    List<HashMap<String, Object>> records = page.getRecords();
                    records.add(map);
                    page.setTotal(total + page.getPages());
                }

            }
        }
        return page;
    }


    public void checkDesign(List<ErpReportDesign> erpReportDesignList,String type){
        boolean isHaveNoSearch = erpReportDesignList.stream().noneMatch(f->f.getOnSearch() &&  "表头".equals(f.getFieldSource()) );
        if(isHaveNoSearch)throw new NuoNiuException("请选择'表头'条件");

        if("_Detail_".equals(type)){
            boolean isHaveNoShow = erpReportDesignList.stream().noneMatch(ErpReportDesign::getOnShow);
            if(isHaveNoShow)throw new NuoNiuException("请选择显示字段");
            boolean isHaveNoDetailShow = erpReportDesignList.stream().noneMatch(f -> "明细".equals(f.getFieldSource()) && f.getOnShow());
            if(isHaveNoDetailShow)throw new NuoNiuException("请选择一个“明细”的显示字段");
        }else if("_Statistic_".equals(type)){
            boolean isHaveNoGroup = erpReportDesignList.stream().noneMatch(ErpReportDesign::getOnGroup);
            if(isHaveNoGroup)throw new NuoNiuException("请选择分组字段");

            boolean isHaveNoSummary = erpReportDesignList.stream().noneMatch(f->f.getIsSummary() && f.getOnSummary());
            if(isHaveNoSummary)throw new NuoNiuException("请选择汇总/合计字段");
            boolean isHaveNoDetailSummary = erpReportDesignList.stream().noneMatch(f->"明细".equals(f.getFieldSource()) && f.getIsSummary() && f.getOnSummary() );
            if(isHaveNoDetailSummary)throw new NuoNiuException("请选择一个“明细”的汇总/合计字段");
        }
    }

    @Override
    public void exportReport(DynamicReportDto dynamicReportDto, HttpServletResponse response) {
        String fileName = "库存单据.xls";
        List<String> filedList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();

        dynamicReportDto.getPage().setSize(-1);
        List<HashMap<String, Object>> dataList = pageReport(dynamicReportDto).getRecords();
        List<HashMap<String, String>> fileList = dynamicReportDto.getFiledList();
        for (HashMap<String, String> filedMap : fileList) {
            if(filedMap.get("dataIndex") != null && !filedMap.get("dataIndex").equals("number")) {
                filedList.add(filedMap.get("dataIndex"));
                titleList.add(filedMap.get("title"));
            }
        }

        ExcelUtils.exportData(titleList.toArray(), fileName, dataList, Arrays.copyOf(filedList.toArray() , filedList.toArray().length, String[].class), response);
    }

    /**
     * 生成动态参数
     * @param paramMap
     * @param dtos
     */
    private void getDynamicParamMap(HashMap<String,Object> paramMap,List<ErpReportDesign> dtos){
        dtos.stream().filter(f-> StringUtils.isNotBlank(f.getValue()) || (null != f.getRangDateVal() && f.getRangDateVal().length == 2) ).forEach(item->{
            String tableNameStr = item.getTableName();
            String[] tableNameSplit = tableNameStr.split(" ");
            String tableAlias = tableNameSplit[1];
            String code = tableAlias + "_" + item.getCode();
            if(StringUtils.isNotBlank(item.getValue())){
                paramMap.put(code,item.getValue());
            }else{
                Object[] rangDateVal = item.getRangDateVal();
                ArrayList rangDate = (ArrayList)rangDateVal[1];
                String startDate = String.valueOf(rangDate.get(0));
                String endDate =String.valueOf(rangDate.get(1));
                paramMap.put(code+ "_startDate",startDate);
                paramMap.put(code+ "_endDate",endDate);
            }
        });
    }
}
